package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.List.OnlineUser;
import l1j.server.Config;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.echo.ClientThread;
import l1j.server.server.model.Instance.L1PcInstance;

/**
 * 人物資料自動保存
 *
 * @author dexc
 *
 */
public class PcAutoSaveTimer extends TimerTask {
	private static final Logger _log = Logger.getLogger(PcAutoSaveTimer.class
			.getName());

	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
			final Collection<ClientThread> allClien = OnlineUser.get().all();
			// 不包含元素
			if (allClien.isEmpty()) {
				return;
			}

			for (final ClientThread client : allClien) {
				int time = client.get_savePc();
				if (time == -1) {
					continue;
				}
				time--;
				this.save(client, time);
			}

		} catch (final Exception e) {
			// _log.error("人物資料自動保存時間軸異常重啟", e);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final PcAutoSaveTimer restart = new PcAutoSaveTimer();
			restart.start();
		}
	}

	/**
	 * 執行人物資料存檔
	 *
	 * @param pc
	 */
	private void save(final ClientThread client, final Integer time) {
		try {
			if (client.get_socket() == null) {
				return;
			}
			if (time > 0) {
				// 更新
				client.set_savePc(time);
			} else {
				client.set_savePc(Config.AUTOSAVE_INTERVAL);
				if (!client._charRestart) {
					final L1PcInstance pc = client.getActiveChar();
					if (pc != null) {
						pc.save();
					}
				}
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, "執行人物資料存檔處理異常 帳號:" + client.getAccountName());
			// _log.debug("執行人物資料存檔處理異常 帳號:" + client.getAccountName());
		}
	}

	public void start() {
		final int timeMillis = 60 * 1000;
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,
				timeMillis, timeMillis);
	}
}
